using System.IdentityModel.Tokens.Jwt;
using FileTransfer.Client.Http.Model;

namespace FileTransferDesktop.Services;

/// <summary>
/// AuthenticationService 的扩展方法，用于支持新的会话管理
/// </summary>
public static class AuthenticationServiceExtensions
{
    /// <summary>
    /// 从 UserResponse 创建 UserInfo
    /// </summary>
    /// <param name="userResponse">API返回的用户信息</param>
    /// <returns>本地存储用的用户信息</returns>
    public static UserInfo ToUserInfo(this UserResponse userResponse)
    {
        return new UserInfo
        {
            Id = userResponse.Id,
            Username = userResponse.Username ?? "",
            Email = userResponse.Email ?? "",
            DisplayName = userResponse.DisplayName ?? "",
            Role = userResponse.Role?.ToString() ?? "",
            Enabled = userResponse.Enabled,
            CreatedAt = userResponse.CreatedAt,
            LastLogin = userResponse.LastLogin,
            AvatarUrl = userResponse.AvatarUrl ?? ""
        };
    }

    /// <summary>
    /// 从 UserInfo 创建 UserResponse (用于向后兼容)
    /// </summary>
    /// <param name="userInfo">本地存储的用户信息</param>
    /// <returns>API格式的用户信息</returns>
    public static UserResponse ToUserResponse(this UserInfo userInfo)
    {
        UserResponse.RoleEnum? role = null;
        if (Enum.TryParse<UserResponse.RoleEnum>(userInfo.Role, out var parsedRole))
        {
            role = parsedRole;
        }

        return new UserResponse(
            id: userInfo.Id,
            username: userInfo.Username,
            email: userInfo.Email,
            displayName: userInfo.DisplayName,
            role: role,
            enabled: userInfo.Enabled,
            createdAt: userInfo.CreatedAt,
            lastLogin: userInfo.LastLogin,
            avatarUrl: userInfo.AvatarUrl
        );
    }

    /// <summary>
    /// 从JWT令牌解析过期时间
    /// </summary>
    /// <param name="token">JWT令牌</param>
    /// <returns>过期时间，如果解析失败则返回null</returns>
    public static DateTime? ParseTokenExpiry(string token)
    {
        try
        {
            var handler = new JwtSecurityTokenHandler();
            if (!handler.CanReadToken(token))
                return null;

            var jwtToken = handler.ReadJwtToken(token);
            return jwtToken.ValidTo;
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>
    /// 生成会话ID
    /// </summary>
    /// <returns>唯一的会话ID</returns>
    public static string GenerateSessionId()
    {
        return $"session_{Guid.NewGuid():N}_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
    }

    /// <summary>
    /// 获取设备信息
    /// </summary>
    /// <returns>设备信息字符串</returns>
    public static string GetDeviceInfo()
    {
        try
        {
            var computerName = Environment.MachineName;
            var osVersion = Environment.OSVersion.ToString();
            var userName = Environment.UserName;

            return $"{computerName} ({osVersion}) - {userName}";
        }
        catch (Exception)
        {
            return "Unknown Device";
        }
    }
}
